<template>
  <div class="register-container">
    <div class="register-box">
      <div class="logo-section">
        <div class="logo-icon">
          <i class="icon-graduation-cap"></i>
        </div>
        <h2>农民技能提升就业培训大数据平台</h2>
        <p>用户注册</p>
      </div>
      
      <form @submit.prevent="handleRegister" class="register-form">
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <i class="icon-alert-circle"></i>
          {{ errorMessage }}
        </div>
        
        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-message">
          <i class="icon-check-circle"></i>
          {{ successMessage }}
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-user"></i>
            用户名
          </label>
          <input
            v-model="registerForm.username"
            type="text"
            required
            placeholder="请输入用户名（3-20个字符）"
            :disabled="loading"
            @blur="validateUsername"
          />
          <span v-if="usernameError" class="field-error">{{ usernameError }}</span>
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-mail"></i>
            邮箱
          </label>
          <input
            v-model="registerForm.email"
            type="email"
            required
            placeholder="请输入邮箱地址"
            :disabled="loading"
            @blur="validateEmail"
          />
          <span v-if="emailError" class="field-error">{{ emailError }}</span>
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-phone"></i>
            手机号
          </label>
          <input
            v-model="registerForm.phone"
            type="tel"
            required
            placeholder="请输入手机号"
            :disabled="loading"
            @blur="validatePhone"
          />
          <span v-if="phoneError" class="field-error">{{ phoneError }}</span>
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-users"></i>
            用户类型
          </label>
          <select
            v-model="registerForm.user_type"
            required
            :disabled="loading"
            class="user-type-select"
          >
            <option value="">请选择用户类型</option>
            <option value="student">学员</option>
            <option value="teacher">教师</option>
            <option value="admin">管理员</option>
          </select>
          <span v-if="userTypeError" class="field-error">{{ userTypeError }}</span>
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-lock"></i>
            密码
          </label>
          <div class="password-input">
            <input
              v-model="registerForm.password"
              :type="showPassword ? 'text' : 'password'"
              required
              placeholder="请输入密码（至少6位）"
              :disabled="loading"
              @blur="validatePassword"
            />
            <button 
              type="button" 
              @click="showPassword = !showPassword"
              class="password-toggle"
              :disabled="loading"
            >
              <i :class="showPassword ? 'icon-eye-off' : 'icon-eye'"></i>
            </button>
          </div>
          <span v-if="passwordError" class="field-error">{{ passwordError }}</span>
          <div class="password-strength">
            <div class="strength-bar">
              <div 
                class="strength-fill" 
                :class="passwordStrength.class"
                :style="{ width: passwordStrength.percentage + '%' }"
              ></div>
            </div>
            <span class="strength-text" :class="passwordStrength.class">
              {{ passwordStrength.text }}
            </span>
          </div>
        </div>
        
        <div class="form-group">
          <label>
            <i class="icon-lock"></i>
            确认密码
          </label>
          <div class="password-input">
            <input
              v-model="registerForm.confirm_password"
              :type="showConfirmPassword ? 'text' : 'password'"
              required
              placeholder="请再次输入密码"
              :disabled="loading"
              @blur="validateConfirmPassword"
            />
            <button 
              type="button" 
              @click="showConfirmPassword = !showConfirmPassword"
              class="password-toggle"
              :disabled="loading"
            >
              <i :class="showConfirmPassword ? 'icon-eye-off' : 'icon-eye'"></i>
            </button>
          </div>
          <span v-if="confirmPasswordError" class="field-error">{{ confirmPasswordError }}</span>
        </div>
        
        <div class="form-options">
          <label class="agreement">
            <input type="checkbox" v-model="registerForm.agreeTerms" required />
            <span class="checkmark"></span>
            我已阅读并同意
            <a href="#" class="terms-link">《用户协议》</a>
            和
            <a href="#" class="privacy-link">《隐私政策》</a>
          </label>
        </div>
        
        <button type="submit" class="register-btn" :disabled="loading || !isFormValid">
          <i v-if="loading" class="icon-loading"></i>
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </form>
      
      <div class="login-link">
        <p>已有账户？ <router-link to="/login">立即登录</router-link></p>
      </div>
      
      <div class="register-footer">
        <p>© 2024 农民技能提升就业培训大数据平台</p>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-1"></div>
      <div class="decoration-2"></div>
      <div class="decoration-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

// 表单验证错误
const usernameError = ref('')
const emailError = ref('')
const phoneError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const userTypeError = ref('')

const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirm_password: '',
  user_type: '',
  agreeTerms: false
})

// API 基础配置
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

// 注册API调用
const registerAPI = async (userData) => {
  const response = await fetch(`${API_BASE_URL}/auth/register`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(userData)
  })
  
  if (!response.ok) {
    let errorData;
    try {
      errorData = await response.json();
    } catch (e) {
      throw new Error('注册失败，服务器返回了无效的响应');
    }
    
    // 处理后端返回的错误信息
    if (errorData.detail) {
      // 将英文错误信息转换为中文
      const errorMessages = {
        'Username already registered': '用户名已被注册',
        'Email already registered': '邮箱已被注册',
        'Phone already registered': '手机号已被注册',
        'passwords do not match': '两次输入的密码不一致',
        'password must be at least 6 characters': '密码长度至少6位',
        'User creation failed due to data integrity error': '用户创建失败，数据完整性错误'
      };
      
      const chineseError = errorMessages[errorData.detail] || errorData.detail;
      throw new Error(chineseError);
    }
    
    throw new Error('注册失败');
  }
  
  return await response.json();
}

// 验证用户名
const validateUsername = () => {
  const username = registerForm.username.trim()
  if (!username) {
    usernameError.value = '用户名不能为空'
    return false
  }
  if (username.length < 3 || username.length > 20) {
    usernameError.value = '用户名长度必须在3-20个字符之间'
    return false
  }
  if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(username)) {
    usernameError.value = '用户名只能包含字母、数字、下划线和中文'
    return false
  }
  usernameError.value = ''
  return true
}

// 验证邮箱
const validateEmail = () => {
  const email = registerForm.email.trim()
  if (!email) {
    emailError.value = '邮箱不能为空'
    return false
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email)) {
    emailError.value = '请输入有效的邮箱地址'
    return false
  }
  emailError.value = ''
  return true
}

// 验证手机号
const validatePhone = () => {
  const phone = registerForm.phone.trim()
  if (!phone) {
    phoneError.value = '手机号不能为空'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    phoneError.value = '请输入有效的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

// 验证密码 - 根据后端要求调整为至少6位
const validatePassword = () => {
  const password = registerForm.password
  if (!password) {
    passwordError.value = '密码不能为空'
    return false
  }
  if (password.length < 6) {
    passwordError.value = '密码长度至少6位'
    return false
  }
  passwordError.value = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (registerForm.confirm_password !== registerForm.password) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }
  confirmPasswordError.value = ''
  return true
}

// 验证用户类型
const validateUserType = () => {
  if (!registerForm.user_type) {
    userTypeError.value = '请选择用户类型'
    return false
  }
  userTypeError.value = ''
  return true
}

// 密码强度计算 - 调整为6位起步
const passwordStrength = computed(() => {
  const password = registerForm.password
  if (!password) return { percentage: 0, text: '', class: '' }
  
  let strength = 0
  
  // 长度检查 - 调整为6位起步
  if (password.length >= 6) strength += 25
  if (password.length >= 8) strength += 15
  
  // 包含小写字母
  if (/[a-z]/.test(password)) strength += 20
  
  // 包含大写字母
  if (/[A-Z]/.test(password)) strength += 20
  
  // 包含数字
  if (/\d/.test(password)) strength += 20
  
  if (strength < 40) {
    return { percentage: strength, text: '弱', class: 'weak' }
  } else if (strength < 80) {
    return { percentage: strength, text: '中等', class: 'medium' }
  } else {
    return { percentage: strength, text: '强', class: 'strong' }
  }
})

// 表单验证
const isFormValid = computed(() => {
  return registerForm.username &&
         registerForm.email &&
         registerForm.phone &&
         registerForm.password &&
         registerForm.confirm_password &&
         registerForm.user_type &&
         registerForm.agreeTerms &&
         !usernameError.value &&
         !emailError.value &&
         !phoneError.value &&
         !passwordError.value &&
         !confirmPasswordError.value &&
         !userTypeError.value
})

// 监听密码变化，重新验证确认密码
watch(() => registerForm.password, () => {
  if (registerForm.confirm_password) {
    validateConfirmPassword()
  }
})

// 处理注册
const handleRegister = async () => {
  // 清除之前的消息
  errorMessage.value = ''
  successMessage.value = ''
  
  // 验证所有字段
  const isUsernameValid = validateUsername()
  const isEmailValid = validateEmail()
  const isPhoneValid = validatePhone()
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()
  const isUserTypeValid = validateUserType()
  
  if (!isUsernameValid || !isEmailValid || !isPhoneValid || !isPasswordValid || !isConfirmPasswordValid || !isUserTypeValid) {
    errorMessage.value = '请检查表单中的错误信息'
    return
  }
  
  loading.value = true
  
  try {
    const userData = {
      username: registerForm.username,
      email: registerForm.email,
      phone: registerForm.phone,
      password: registerForm.password,
      confirm_password: registerForm.confirm_password,
      user_type: registerForm.user_type
    }
    
    const response = await registerAPI(userData)
    
    successMessage.value = '注册成功！请使用您的账号登录...'
    
    // 注册成功后跳转到登录页面，并预填用户名
    setTimeout(() => {
      router.push({
        path: '/login',
        query: { username: registerForm.username }
      })
    }, 2000)
    
  } catch (error) {
    console.error('注册失败:', error)
    errorMessage.value = error.message || '注册失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 使用与登录页面相似的样式 */
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.decoration-1,
.decoration-2,
.decoration-3 {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.decoration-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  right: 10%;
  animation: float 6s ease-in-out infinite;
}

.decoration-2 {
  width: 150px;
  height: 150px;
  bottom: 20%;
  left: 15%;
  animation: float 8s ease-in-out infinite reverse;
}

.decoration-3 {
  width: 100px;
  height: 100px;
  top: 60%;
  right: 20%;
  animation: float 10s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.register-box {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 480px;
  position: relative;
  max-height: 90vh;
  overflow-y: auto;
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.logo-section h2 {
  margin: 0 0 8px 0;
  color: #1F2937;
  font-size: 20px;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 错误和成功提示样式 */
.error-message {
  background: #FEF2F2;
  border: 1px solid #FECACA;
  color: #DC2626;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  animation: shake 0.5s ease-in-out;
}

.success-message {
  background: #F0FDF4;
  border: 1px solid #BBF7D0;
  color: #16A34A;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group label i {
  color: #6B7280;
}

.form-group input,
.user-type-select {
  padding: 12px 16px;
  border: 2px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.form-group input:focus,
.user-type-select:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-group input:disabled,
.user-type-select:disabled {
  background-color: #F9FAFB;
  cursor: not-allowed;
}

.user-type-select {
  background: white;
  cursor: pointer;
}

.password-input {
  position: relative;
}

.password-toggle {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6B7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: color 0.2s;
}

.password-toggle:hover:not(:disabled) {
  color: #374151;
}

.field-error {
  color: #DC2626;
  font-size: 12px;
  margin-top: 4px;
}

/* 密码强度指示器 */
.password-strength {
  margin-top: 8px;
}

.strength-bar {
  height: 4px;
  background: #E5E7EB;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #EF4444;
}

.strength-fill.medium {
  background: #F59E0B;
}

.strength-fill.strong {
  background: #10B981;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
}

.strength-text.weak {
  color: #EF4444;
}

.strength-text.medium {
  color: #F59E0B;
}

.strength-text.strong {
  color: #10B981;
}

.form-options {
  margin: 8px 0;
}

.agreement {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #374151;
  line-height: 1.5;
}

.agreement input {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #D1D5DB;
  border-radius: 4px;
  position: relative;
  transition: all 0.2s;
  flex-shrink: 0;
  margin-top: 2px;
}

.agreement input:checked + .checkmark {
  background: #4F46E5;
  border-color: #4F46E5;
}

.agreement input:checked + .checkmark::after {
  content: '✓';
  color: white;
  font-size: 12px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.terms-link,
.privacy-link {
  color: #4F46E5;
  text-decoration: none;
  transition: color 0.2s;
}

.terms-link:hover,
.privacy-link:hover {
  color: #4338CA;
}

.register-btn {
  padding: 14px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.register-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.login-link {
  text-align: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #E5E7EB;
}

.login-link p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.login-link a {
  color: #4F46E5;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.2s;
}

.login-link a:hover {
  color: #4338CA;
}

.register-footer {
  margin-top: 20px;
  text-align: center;
}

.register-footer p {
  margin: 0;
  color: #6B7280;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-container {
    padding: 16px;
  }
  
  .register-box {
    padding: 32px 24px;
  }
  
  .logo-section h2 {
    font-size: 18px;
  }
}
</style>